#https://leetcode.cn/leetbook/read/array-and-string/cxqdh/
#2024/11/14
class Solution:
    def merge(self, intervals):
        """
        :type intervals: List[List[int]]
        :rtype: List[List[int]]
        """
        if  intervals is None :
            return []
        intervals.sort(key=lambda x:x[0])
        merge=[]
        for i in intervals:
            if not merge or i[0]>merge[-1][1]:
                merge.append(i)
            else:
                merge[-1][1]=max(merge[-1][1],i[1])     
        return merge
    

    def merge1(self, intervals):
        """
        :type intervals: List[List[int]]
        :rtype: List[List[int]]
        """
        # 如果区间列表为空，直接返回空列表
        if not intervals:
            return []

        # 按照起始位置对区间进行排序
        intervals.sort(key=lambda x: x[0])

        # 初始化结果列表
        merged = []

        for interval in intervals:
            # 如果结果列表为空，或者当前区间的起始位置大于结果列表中最后一个区间的结束位置
            if not merged or merged[-1][1] < interval[0]:
                merged.append(interval)
            else:
                # 否则，说明有重叠，更新结果列表中最后一个区间的结束位置
                merged[-1][1] = max(merged[-1][1], interval[1])

        return merged

intervals1 = [[1,3],[2,6],[8,10],[15,18]]
intervals2 = [[1,4],[4,5]]
solution=Solution()
print(solution.merge(intervals1))
print(solution.merge(intervals2))